package com.lam.monitor.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.lam.common.base.controller.BaseController;
import com.lam.common.base.domain.LoginUser;
import com.lam.common.base.domain.Result;
import com.lam.common.base.page.PageVo;
import com.lam.common.base.page.TableHelper;
import com.lam.common.components.dict.annotation.DictAutoTransfer;
import com.lam.common.context.AuthTypeEnum;
import com.lam.common.context.TokenUtils;
import com.lam.common.utils.DateUtil;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.NumberUtil;
import com.lam.framework.annotation.ParamInject;
import com.lam.framework.operLog.annotation.Log;
import com.lam.framework.operLog.enums.BusinessType;
import com.lam.framework.operLog.enums.LogSave;
import com.lam.monitor.domain.UserOnline;

/**
 * 在线用户监控
 * 
 */
@Log(title = "在线用户")
@ParamInject
@RestController
@RequestMapping("/${adminPath}/monitor/onlineUser")
public class UserOnlineController extends BaseController {

	@DictAutoTransfer
	@Log(oper="在线用户查询")
	@PreAuthorize("@ss.hasPm('monitor:onlineUser:list')")
	@GetMapping("/list")
	public Result list(String operatorType, String keywords) {
		PageVo pageVo = TableHelper.getPageVo();
		List<LoginUser> loginUserList = TokenUtils.getLoginUserList(operatorType, keywords, pageVo.getPageNum(), pageVo.getPageSize());
		String curToken = TokenUtils.getToken();
		
		List<UserOnline> userOnlineList = new ArrayList<>();
		UserOnline userOnline;
		int no = 0;
    	for (LoginUser loginUser : loginUserList) {
    		userOnline = JsonUtil.toJavaObject(loginUser, UserOnline.class);
    		userOnlineList.add(userOnline);
    		userOnline.setNo(++no);
    		userOnline.setTokenId(loginUser.getToken());
    		userOnline.setLoginTimeStr(DateUtil.formatDateTime(new Date(loginUser.getLoginTime())));
    		userOnline.setOnlineTimeStr(DateUtil.convertTimeLong((System.currentTimeMillis() - loginUser.getLoginTime())/1000*1000));
    		userOnline.setExpiresAtStr(DateUtil.formatDateTime(new Date(loginUser.getExpiresAt())));
    		userOnline.setExpireTimeStr(DateUtil.convertTimeLong(loginUser.getExpireTime()*1000));
    		userOnline.setOperatorType(AuthTypeEnum.valueFromAuthType(loginUser.getAuthType()).getTokenPrefix());
    		if(curToken.equals(loginUser.getToken())) {
    			userOnline.setUsername(userOnline.getUsername()+"(当前用户)");
    		}
    		userOnline.setCurUser(curToken.equals(loginUser.getToken()));
		}
    	userOnlineList.sort((t1, t2)->NumberUtil.compare(t1.getLoginTime(), t2.getLoginTime()));
		return Result.ok(getTableData(userOnlineList));
	}

	/**
	 * 强退用户
	 */
	@PreAuthorize("@ss.hasPm('monitor:onlineUser:forceLogout')")
	@Log(businessType = BusinessType.OTHER, oper = "强退用户", logSave = LogSave.YES)
	@DeleteMapping("/{tokenId}")
	public Result forceLogout(@PathVariable String tokenId) {
		
		String curToken = TokenUtils.getToken();
		
		String[] ss = tokenId.split(",");
		int n = 0;
		for (String token : ss) {
			if(curToken.equals(token)) {
				continue;
			}
			TokenUtils.logout(token);
			n++;
		}
		
		return n > 0 ? Result.ok("强退成功！（注：当前用户不能被强退）") : Result.fail("强退失败！（当前用户不能被强退）");
	}
}
